package com.sanjiahantang.youjiarole.module.decorate.adapters;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.dialog.CommonDialog;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.MyGridView;
import com.sanjiahantang.uilibrary.views.MyListView;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.config.StaticValue;
import com.sanjiahantang.youjiarole.module.decorate.beans.DecorateManageBean;
import com.sanjiahantang.youjiarole.module.decorate.presenters.DecorateManagePresenter;
import com.sanjiahantang.youjiarole.module.decorate.views.impl.CheckPicActivity;
import com.sanjiahantang.youjiarole.module.decorate.views.impl.SupervisionCheckActivity;
import com.sanjiahantang.youjiarole.module.me.scheme.views.impl.MeSchemeActivity;
import com.sanjiahantang.youjiarole.module.me.scheme.views.impl.MeSchemeCaseDetailActivity;
import com.sanjiahantang.youjiarole.module.project.views.impl.ProjectActivity;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zy on 2017/9/15.
 */

public class FlowAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements StaticValue{

    public static final int TYPE_DONE = 2;
    public static final int TYPE_DOING = 1;
    public static final int TYPE_NOT_DO = 0;

    private int[] grayIcons = new int[]{
            R.drawable.i_house_gray_5,
            R.drawable.i_house_gray_4,
            R.drawable.i_house_gray_3,
            R.drawable.i_house_gray_2,
            R.drawable.i_house_gray_1
    };


    private int[] greenIcons = new int[]{
            R.drawable.i_house_green_5,
            R.drawable.i_house_green_4,
            R.drawable.i_house_green_3,
            R.drawable.i_house_green_2,
            R.drawable.i_house_green_1
    };

    private String[] titleNames = new String[]{
            "竣工验收",
            "主材验收",
            "中期验收",
            "隐蔽工程验收",
            "进场交底"
    };

    private String[] roleName = new String[]{
            "设计师",
            "项目经理",
            "监理"
    };

    private int colorTextGray,colorBlack,colorGray,colorGreen;
    private int vLineGray,vLineGreen;
    private DecorateManageBean.Data dmData;
    private LayoutInflater inflater;
    private Context context;
    private HashMap<Integer,String> roleMap,actionMap,waitMap;
    private DecorateManagePresenter presenter;

    private HashMap<Integer,Integer> groupIdMap;
    public FlowAdapter(Context context, DecorateManageBean.Data data, DecorateManagePresenter presenter){
        this.context = context;
        this.presenter = presenter;
        inflater = LayoutInflater.from(context);
        Resources res = context.getResources();
        vLineGray = R.drawable.x_dot_line_gray;
        vLineGreen = R.drawable.x_dot_line_green;
        colorTextGray = res.getColor(R.color.gray);
        colorBlack = res.getColor(R.color.black);
        colorGray = res.getColor(R.color.gray_bf);
        colorGreen = res.getColor(R.color.colorPrimary);
        this.dmData = data;

        roleMap = new HashMap<>();
        roleMap.put(0,"客户");
        roleMap.put(1,"项目经理");
        roleMap.put(2,"监理");

        actionMap = new HashMap<>();
        waitMap = new HashMap<>();
        actionMap.put(10,"发起验收");
        actionMap.put(20,"完成验收");
        actionMap.put(30,"确认验收");
        actionMap.put(40,"发起验收");
        actionMap.put(50,"完成验收");
        actionMap.put(60,"确认验收");
        actionMap.put(65,"中期付款");
        actionMap.put(70,"发起验收");
        actionMap.put(80,"完成验收");
        actionMap.put(90,"确认验收");
        actionMap.put(100,"发起验收");
        actionMap.put(110,"完成验收");
        actionMap.put(120,"确认验收");
        actionMap.put(130,"发起验收");
        actionMap.put(140,"完成验收");
        actionMap.put(150,"确认验收");
        actionMap.put(155,"竣工付款");
        actionMap.put(156,"评价");
        actionMap.put(160,"增项");
        actionMap.put(170,"减项");
        actionMap.put(180,"申请更换项目经理");
        actionMap.put(190,"申请更换监理");
        actionMap.put(200,"已更换");
        actionMap.put(210,"已更换");

        waitMap.put(10,"等待发起");
        waitMap.put(20,"等待验收");
        waitMap.put(30,"等待确认");
        waitMap.put(40,"等待发起");
        waitMap.put(50,"等待验收");
        waitMap.put(60,"等待确认");
        waitMap.put(65,"等待付款");
        waitMap.put(70,"等待发起");
        waitMap.put(80,"等待验收");
        waitMap.put(90,"等待确认");
        waitMap.put(100,"等待发起");
        waitMap.put(110,"等待验收");
        waitMap.put(120,"等待确认");
        waitMap.put(130,"等待发起");
        waitMap.put(140,"等待验收");
        waitMap.put(150,"等待确认");
        waitMap.put(155,"等待付款");
        waitMap.put(156,"等待评价");


//流程节点分组ID 0  工程开启 1 进场复查 2 中期验收3 主材验收4 待竣工前自检验收5 竣工验收  6 其他 （增项 减项 投诉）
        groupIdMap = new HashMap<>();
        groupIdMap.put(1,4);
        groupIdMap.put(2,3);
        groupIdMap.put(3,2);
        groupIdMap.put(4,1);
        groupIdMap.put(5,0);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        List<DecorateManageBean.Step> flow = null;
        switch (viewType){
            case 0:
                flow = dmData.getCompletionList();
                break;
            case 1:
                flow = dmData.getBeforeCompletionList();
                break;
            case 2:
                flow = dmData.getMaterialList();
                break;
            case 3:
                flow = dmData.getMetaphaseList();
                break;
            case 4:
                flow = dmData.getReviewList();
                break;
            case -1:
                return new FlowViewHolder(inflater.inflate(R.layout.fragment_decorate_detail,null),dmData,context);
        }
        return new FlowViewHolder(inflater.inflate(R.layout.item_flow,null),viewType,flow);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemViewType(int position) {
        return (position - 1 < 0) ? (position - 1):(grayIcons.length - position);
    }

    @Override
    public int getItemCount() {
        return grayIcons.length + 1;
    }

    private class FlowViewHolder extends RecyclerView.ViewHolder{

        public FlowViewHolder(View itemView, final int type, final List<DecorateManageBean.Step> flow) {
            super(itemView);
            ImageView ivFlowHouse = (ImageView) itemView.findViewById(R.id.ivFlowHouse);
            View view_line = itemView.findViewById(R.id.view_Line);
            TextView txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            MyListView lvFlow = (MyListView) itemView.findViewById(R.id.lvFlow);

//            final int groupId = dmData.getGroupId();
            int gId = 0;
            if (dmData.getReviewList() != null && dmData.getReviewList().size() > 0){
                gId = 1;
            }

            if (dmData.getMetaphaseList() != null && dmData.getMetaphaseList().size() > 0){
                gId = 2;
            }

            if (dmData.getMaterialList() != null && dmData.getMaterialList().size() > 0){
                gId = 3;
            }

            if (dmData.getBeforeCompletionList() != null && dmData.getBeforeCompletionList().size() > 0){
                gId = 4;
            }

            if (dmData.getCompletionList() != null && dmData.getCompletionList().size() > 0){
                gId = 5;
            }
            final int groupId = gId;

            txtTitle.setText(titleNames[type]);
            if(!(type < groupIdMap.get(groupId))){
                ivFlowHouse.setImageResource(greenIcons[type]);
                view_line.setBackgroundResource(vLineGreen);
                txtTitle.setTextColor(colorBlack);
                view_line.setVisibility(View.GONE);
                itemView.findViewById(R.id.vLineGreen).setVisibility(View.VISIBLE);
            }else {
                ivFlowHouse.setImageResource(grayIcons[type]);
                view_line.setBackgroundResource(vLineGray);
                txtTitle.setTextColor(colorTextGray);
            }

            if (type == 0){
                view_line.setVisibility(View.GONE);
                itemView.findViewById(R.id.vLineGreen).setVisibility(View.GONE);
            }

//            FrameLayout flDotLine = (FrameLayout) itemView.findViewById(R.id.flDotL

            lvFlow.setAdapter(new QuickAdapter<DecorateManageBean.Step>(context,R.layout.item_step,flow) {
                @Override
                protected void convert(BaseAdapterHelper helper, final DecorateManageBean.Step item) {


                    //公用部分
                    if(helper.getPosition() == 0){
                        helper.setVisible(R.id.flLineTop,false);
                    }else {
                        helper.setVisible(R.id.flLineTop,true);
                    }

                    if(helper.getPosition() == getCount() - 1){
                        helper.getView(R.id.flLineBottom).setVisibility(View.INVISIBLE);
                        helper.setVisible(R.id.vLineDivider,false);
                    }else{
                        helper.setVisible(R.id.flLineBottom,true);
                        helper.setVisible(R.id.vLineDivider,true);
                    }

                    helper.setText(R.id.txtRole,roleMap.get(item.getRoleId()));
                    if ("1".equals(item.getPassStateId())){
                        helper.setText(R.id.txtAction,item.getEvent());
                    }else{
                        helper.setText(R.id.txtAction,actionMap.get(item.getStatusId()));
                    }

                    helper.setTextColor(R.id.txtAction,colorGray);
                    helper.setBackgroundRes(R.id.vStep,R.drawable.x_ring_gray);
                    helper.setVisible(R.id.llBtnGroup,false);
                    helper.setVisible(R.id.txtAction,true);
                    helper.setVisible(R.id.llAction,true);
                    if (item.getCreateTime() != null && item.getCreateTime().length() >= "yyyy-MM-dd".length()){
                        helper.setText(R.id.txtDateTime,item.getCreateTime().substring(0,"yyyy-MM-dd".length()));
                    }else{
                        helper.setText(R.id.txtDateTime,"");
                    }

                    helper.setVisible(R.id.txtDateTime,true);

                    String role = "";
                    String myPhone = SPUtils.get(context,SPConfig.PHONE,"").toString();
                    if (dmData.getIsSubcontractProject() == 1){
                        if (myPhone.equals(dmData.getProjectPhone())){
                            role += "1,";
                        }
                    }else{
                        if (myPhone.equals(dmData.getRoleProjectPhone())){
                            role += "1,";
                        }
                    }


                    if (myPhone.equals(dmData.getRoleSupervisionPhone())){
                        role += "2,";
                    }

                    if(type == groupIdMap.get(groupId)){
                        //当前流程
                        if(helper.getPosition() == flow.size() - 1){
                            if (role.contains(String.valueOf(item.getRoleId()))
                                    && (item.getRoleId() != 0)){

                                helper.setBackgroundRes(R.id.vStep,R.drawable.x_circle_green);
                                helper.setVisible(R.id.txtAction,false);
                                helper.setVisible(R.id.llBtnGroup,true);
                                helper.setBackgroundRes(R.id.btnOK,R.drawable.x_shape_green);
                                helper.setText(R.id.btnOK,actionMap.get(item.getStatusId()));

                                //隐藏最后按钮
                                if (!TextUtils.isEmpty(dmData.getOrderStatusId())){
                                    int statusId = Integer.valueOf(dmData.getOrderStatusId());
                                    if (item.getStatusId() == 156 && statusId > 30){
                                        helper.setVisible(R.id.llAction,true);
                                        helper.setVisible(R.id.txtAction,true);
                                        helper.setVisible(R.id.llBtnGroup,false);
                                        helper.setText(R.id.txtAction,actionMap.get(item.getStatusId()));
                                        helper.setTextColor(R.id.txtAction,colorBlack);
                                    }
                                }


                                helper.setOnClickListener(R.id.btnOK, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (item.getRoleId() == 2){
                                            context.startActivity(new Intent(context, SupervisionCheckActivity.class)
                                                    .putExtra("piId",item.getPiId())
                                                    .putExtra("priId",item.getPriId())
                                            );
                                        }else{
                                            Utils.showDialog((Activity) context, "", "确认验收?", "", "", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    Utils.dismissDialog();
                                                    if (v.getId() == CommonDialog.ID_POSITIVE){
                                                        presenter.updateEngnieeInfo(context,item.getPiId(),item.getPriId());
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                                helper.setTextColor(R.id.txtAction,colorGreen);
                                helper.setVisible(R.id.llAction,false);

                                if (10 == item.getStatusId()){
                                    if (TextUtils.isEmpty(dmData.getRoleProjectPhone()) || TextUtils.isEmpty(dmData.getRoleSupervisionPhone())){
                                        helper.setOnClickListener(R.id.btnOK,null);
                                        helper.setBackgroundRes(R.id.btnOK,R.drawable.x_shape_gray);
                                    }
                                }

                            }else{
                                helper.setTextColor(R.id.txtAction,colorTextGray);
                                helper.getView(R.id.ivArrow).setVisibility(View.INVISIBLE);
                                helper.getView().setOnClickListener(null);
                                helper.setText(R.id.txtAction,waitMap.get(item.getStatusId()));
                                helper.setVisible(R.id.txtDateTime,false);
                                if (!TextUtils.isEmpty(dmData.getOrderStatusId()) && item.getStatusId() >= 156){
                                    int statusId = Integer.valueOf(dmData.getOrderStatusId());
                                    if (statusId > 30){
                                        helper.setVisible(R.id.txtDateTime,true);
                                        helper.setText(R.id.txtAction,"\u3000评价\u3000");
                                    }
                                }

                            }

                            if (item.getStatusId() > 150 && dmData.getIsOfficial() == 0){
                                helper.setVisible(R.id.txtDateTime,true);
                                helper.setText(R.id.txtAction,"已完工　");
                            }

                        }else {
                            if(role.contains(String.valueOf(item.getRoleId()))){
                                helper.setTextColor(R.id.txtAction,colorBlack);
                            }else{
                                helper.setTextColor(R.id.txtAction,colorTextGray);
                            }

                            if (item.getRoleId() == 2){
                                helper.setVisible(R.id.ivArrow,true);
                                helper.getView().setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        context.startActivity(new Intent(context, CheckPicActivity.class)
                                                .putExtra(KEY_ID,item.getPriId())
                                                .putExtra(KEY_PARAM,item.getRemark())
                                                .putExtra(KEY_TITLE,actionMap.get(item.getStatusId()))
                                        );
                                    }
                                });
                            }else{
                                helper.getView(R.id.ivArrow).setVisibility(View.INVISIBLE);
                                helper.getView().setOnClickListener(null);
                            }
                        }
                    } else {
                        if(role.contains(String.valueOf(item.getRoleId()))){
                            helper.setTextColor(R.id.txtAction,colorBlack);
                        }else{
                            helper.setTextColor(R.id.txtAction,colorTextGray);
                        }

                        if (item.getRoleId() == 2){
                            helper.setVisible(R.id.ivArrow,true);
                            helper.getView().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    context.startActivity(new Intent(context, CheckPicActivity.class)
                                            .putExtra(KEY_ID,item.getPriId())
                                            .putExtra(KEY_PARAM,item.getRemark())
                                            .putExtra(KEY_TITLE,actionMap.get(item.getStatusId()))
                                    );
                                }
                            });
                        }else{
                            helper.getView(R.id.ivArrow).setVisibility(View.INVISIBLE);
                            helper.getView().setOnClickListener(null);
                        }
                    }

                    if (role.contains(String.valueOf(item.getRoleId()))){
                        helper.setTextColor(R.id.txtRole,colorBlack);
                    }else {
                        helper.setTextColor(R.id.txtRole,colorTextGray);
                    }
                }
            });
        }


        public FlowViewHolder(View itemView, DecorateManageBean.Data bean, final Context context){
            super(itemView);

            QuickAdapter<DecorateManageBean.Role> participantAdapter;
            MyGridView participantGrid = (MyGridView) itemView.findViewById(R.id.participantGrid);
            HashMap<String,DecorateManageBean.Role> roleHashMap = bean.getRoleList().get(0);
            if (bean.getRoleSubcontractList() != null && bean.getRoleSubcontractList().size() > 0){
                roleHashMap = bean.getRoleSubcontractList().get(0);
            }

            List<DecorateManageBean.Role> list = new ArrayList<>();
            String designerPhone = bean.getRoleDesignerPhone();
            final String projectPhone = bean.getRoleProjectPhone();
            String supervisionPhone = bean.getRoleSupervisionPhone();

            TextView txtEngineNumber = (TextView) itemView.findViewById(R.id.txtEngineNumber);
            if (bean.getEngineNumber() != null){
                txtEngineNumber.setText("项目编号: " + bean.getEngineNumber());
            }else{
                txtEngineNumber.setText("项目编号: ");
            }
            itemView.findViewById(R.id.vTop).setBackgroundResource(R.color.white);

            if (designerPhone != null && roleHashMap.containsKey("designer")){
                DecorateManageBean.Role roleDesigner = roleHashMap.get("designer");
                roleDesigner.setType(0);
                list.add(roleDesigner);
                if (roleHashMap.containsKey("engniee")){
                    DecorateManageBean.Role roleEngniee = roleHashMap.get("engniee");
                    roleEngniee.setType(1);
                    list.add(roleEngniee);
                }else if (designerPhone.equals(projectPhone)){
                    DecorateManageBean.Role roleEngniee = roleHashMap.get("designer");
                    roleEngniee.setType(1);
                    list.add(roleEngniee);
                }

                if (roleHashMap.containsKey("supervision")){
                    DecorateManageBean.Role roleSupervision = roleHashMap.get("supervision");
                    roleSupervision.setType(2);
                    list.add(roleSupervision);
                }else if (designerPhone.equals(supervisionPhone)){
                    DecorateManageBean.Role roleSupervision = roleHashMap.get("designer");
                    roleSupervision.setType(2);
                    list.add(roleSupervision);
                }
            }
            participantAdapter = new QuickAdapter<DecorateManageBean.Role>(context,R.layout.item_participant,list) {
                @Override
                protected void convert(BaseAdapterHelper helper, DecorateManageBean.Role item) {
                    ImageView ivPhoto = helper.getView(R.id.ivPhoto);
                    Picasso.with(context).load(FileUtils.rePath(item.getUrl()))
                            .placeholder(R.drawable.i_head_default)
                            .into(ivPhoto);

                    helper.setText(R.id.txtRole,roleName[item.getType()]);
                    helper.setText(R.id.txtName,item.getUserName());
                }
            };


            participantGrid.setAdapter(participantAdapter);
            participantGrid.setSelector(R.color.transparent);
            itemView.findViewById(R.id.panelPlan).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    Intent intent = new Intent(context, MeSchemeCaseDetailActivity.class);
                    intent.putExtra(KEY_ID,dmData.getPpId());
                    if (TextUtils.isEmpty(projectPhone)){
                        intent.putExtra("projectid","0");
                        intent.putExtra("totalstateid","2");
                    }
                    context.startActivity(intent);
                }
            });

            if (bean.getProjectInfo() != null){
                itemView.findViewById(R.id.panelPlan).setVisibility(View.VISIBLE);
                ImageView ivCaseMain = (ImageView) itemView.findViewById(R.id.ivCaseMain);
                Picasso.with(context).load(FileUtils.rePath(bean.getProjectInfo().getUrl())).placeholder(R.drawable.i_match).into(ivCaseMain);

                TextView tv_case_detail = (TextView) itemView.findViewById(R.id.tv_case_detail);
                itemView.findViewById(R.id.llCollect).setVisibility(View.GONE);
                String detail = null;
                if (!TextUtils.isEmpty(bean.getProjectInfo().getApartmentTypeName())){
                    detail = bean.getProjectInfo().getApartmentTypeName();
                }

                if (!TextUtils.isEmpty(bean.getProjectInfo().getLikeStyleName())){
                    if (!TextUtils.isEmpty(detail)){
                        detail = detail + " , " + bean.getProjectInfo().getLikeStyleName();
                    }else{
                        detail = bean.getProjectInfo().getLikeStyleName();
                    }
                }

                if (!TextUtils.isEmpty(detail)){
                    tv_case_detail.setText(detail);
                }
            }else{
                itemView.findViewById(R.id.panelPlan).setVisibility(View.GONE);
            }

        }

    }
}
